package com.newflypig.jblog.service.impl;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.newflypig.jblog.dao.IBaseDAO;
import com.newflypig.jblog.dao.ITagDAO;
import com.newflypig.jblog.model.BlogCommon;
import com.newflypig.jblog.model.Tag;
import com.newflypig.jblog.service.ITagService;

@Service("tagService")
public class TagServiceImpl extends BaseServiceImpl<Tag> implements ITagService{

	@Autowired
	private ITagDAO tagDao;
	
	@Autowired
	private BlogCommon blogCommon;
	
	@Override
	protected IBaseDAO<Tag> getDao() {
		return this.tagDao;
	}

	@Override
	public Tag findByTitle(String tagTitle) {
		List<Tag> list =this.tagDao.findByDC(
			DetachedCriteria.forClass(Tag.class)
			.add(Restrictions.eq("title", tagTitle).ignoreCase())
		);
		return list.isEmpty() ? null : list.get(0);
	}

	@Override
	public void makeConnect(Integer tagId, Integer articleId) {
		this.tagDao.makeConnect(tagId, articleId);
	}

	@Override
	public void cleanConnect(Integer articleId) {
		this.tagDao.cleanConnect(articleId);
	}

	@Override
	public List<String> findTagUrls() {
		List<Tag> tagsList = this.tagDao.findByDC(
			DetachedCriteria.forClass(Tag.class, "tag")
			.setProjection(Projections.property("tag.urlName").as("urlName"))
			.setResultTransformer(Transformers.aliasToBean(Tag.class))
		);
		
		List<String> urlsList = new ArrayList<String>();
		
		tagsList.stream().forEach(tag -> {
			if(!StringUtils.isEmpty(tag.getUrlName()))
				try {
					urlsList.add(
						"http://" + blogCommon.getBlogUrl() + "/tag/" + URLEncoder.encode(tag.getUrlName(), "UTF-8")
					);
				} catch (Exception e) {
					e.printStackTrace();
				}
		});
				
		return urlsList;
	}

	@Override
	public List<String> findAllFromTable() {
		return this.tagDao.findAllFromTable();
	}
}
